package com.pocketsweet.ui;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.DeleteCallback;
import com.avos.avoscloud.FindCallback;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.pocketsweet.R;
import com.pocketsweet.MLApplication;
import com.pocketsweet.MLContext;
import com.pocketsweet.chat.ui.activity.BaseActivity;
import com.pocketsweet.chatlib.controller.MolianContactManager;
import com.pocketsweet.chatlib.controller.MolianContactManager.MoLianAgreeFridedListener;
import com.pocketsweet.chatui.Constant;
import com.pocketsweet.model.MLFriendApply;
import com.pocketsweet.model.MLUserLike;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.uilib.AutoListView;
import com.pocketsweet.ui.uilib.HeaderLayout;
import com.pocketsweet.ui.uilib.LoadingDailog;
import com.pocketsweet.ui.uilib.MyAlertDialog;
import com.pocketsweet.ui.uilib.HeaderLayout.HeaderStyle;
import com.pocketsweet.ui.uilib.HeaderLayout.onLeftContainerListener;
import com.pocketsweet.ui.uilib.HeaderLayout.onRightContainerListener;
import com.pocketsweet.ui.uilib.adapter.NewLoverListAdapter;
import com.pocketsweet.utils.ShareReferanceUtils;
import com.pocketsweet.utils.ToolKits;

@ContentView(R.layout.activity_new_lover)
public class NewLover extends BaseActivity implements OnItemClickListener {

	@ViewInject(R.id.newLoverListview)
	private static ListView newLoverListview;

	@ViewInject(R.id.mainHeader)
	private static HeaderLayout header;

	@ViewInject(R.id.linBlank)
	private static LinearLayout linBlank;

	public static LoadingDailog loading;
	private NewLoverListAdapter newLoverListAdapter;
	private List<MLFriendApply> newLoverList = new ArrayList<MLFriendApply>();
	private Context ctx;
	AVQuery<MLFriendApply> querys;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ViewUtils.inject(this);
		ctx = this;
		newLoverListAdapter = new NewLoverListAdapter(NewLover.this,
				newLoverList);
		newLoverListview = (ListView) findViewById(R.id.newLoverListview);
		header = (HeaderLayout) findViewById(R.id.mainHeader);
		linBlank = (LinearLayout) findViewById(R.id.linBlank);
		newLoverListview.setAdapter(newLoverListAdapter);
		clear();
		MolianContactManager.getInstance().setMoLianAgreeFridedListener(
				new MoLianAgreeFridedListener() {

					@Override
					public void onAgressFail() {
						ToolKits.toast(ctx, "发送失败");
						loading.dismiss();
					}

					@Override
					public void onAgreeeSucess(String applyId, final View v) {
						AVQuery<MLFriendApply> apply = new AVQuery<MLFriendApply>(
								"MLFriendApply");
						apply.whereEqualTo("objectId", applyId);
						apply.deleteAllInBackground(new DeleteCallback() {

							@SuppressLint("NewApi")
							@Override
							public void done(AVException e) {
								if (e == null) {
									loading.dismiss();
									TextView view = ((TextView) v);

									view.setTextColor(view.getResources()
											.getColor(R.color.text_999));
									view.setBackground(null);
									view.setText("已同意");
								} else {
									loading.dismiss();
								}
							}
						});

					}
				});
		getNewLoverList();
		setHeaderFunction();
	}

//	private void clear() {
//		ShareReferanceUtils unreadInviteCount = new ShareReferanceUtils(
//				MLApplication.getContext(), "UnreadInvite_"
//						+ UserService.getCurrentUserId());
//		unreadInviteCount.setIntValue("count", 0);
//	}
	
	private void clear() {
		// Log.e("========", MLApplication.getInstance().getContactList()
		// .toString()
		// + " 111");
		// Log.e("========",
		// MLApplication.getInstance().getContactList()
		// .get(Constant.NEW_FRIENDS_USERNAME).toString()
		// + " 222");
		EMConversation conversation = EMChatManager.getInstance()
				.getConversation(Constant.NEW_FRIENDS_USERNAME);
		conversation.resetUnreadMsgCount();
	}

	public void setHeaderFunction() {
		header = (HeaderLayout) findViewById(R.id.mainHeader);
		header.init(HeaderStyle.IMG_TITLE_TEXT);
		header.setRightText("忽略所有");
		header.setMiddleText("新的恋人");
		header.setLeftContainerClickListener(new onLeftContainerListener() {

			@Override
			public void onClick() {
				NewLover.this.finish();
			}
		});
		header.setRighttContainerClickListener(new onRightContainerListener() {

			@Override
			public void onClick() {
				if (newLoverList == null || newLoverList.size() <= 0) {
					return;
				}
				final MyAlertDialog dialogCache = new MyAlertDialog(
						NewLover.this).builder().setMsg("是忽略所有新恋人的申请？")
						.setTitle("忽略所有")
						.setNegativeButton("取消", new OnClickListener() {
							@Override
							public void onClick(View v) {

							}
						});
				dialogCache.setPositiveButton("确定", new OnClickListener() {
					@SuppressLint("SimpleDateFormat")
					@Override
					public void onClick(View v) {
						if (newLoverList == null || newLoverList.size() == 0) {
							return;
						}
						loading.setText("加载中");
						loading.show();
						querys.deleteAllInBackground(new DeleteCallback() {

							@Override
							public void done(AVException e) {
								loading.dismiss();
								if (e == null) {
									newLoverList.clear();
									newLoverListAdapter.notifyDataSetChanged();
									linBlank.setVisibility(View.VISIBLE);
								} else {
									ToolKits.toast(NewLover.this, "网络错误，请重试");
								}
							}
						});

					}
				});
				dialogCache.show();
			}
		});

	}

	private void getNewLoverList() {
		loading = ToolKits.createLoadingDialog(NewLover.this, "提交中..");
		loading.setText("正在获取中");
		loading.show();

		querys = new AVQuery<MLFriendApply>("MLFriendApply");
		querys.whereEqualTo("user", UserService.getCurrentUser());
		querys.include("applier");
		querys.orderByDescending("createdAt");
		querys.findInBackground(new FindCallback<MLFriendApply>() {

			@Override
			public void done(List<MLFriendApply> mlFriendApplies, AVException e) {
				if (e == null) {
					if (mlFriendApplies.size() > 0) {
						linBlank.setVisibility(View.GONE);
						loading.dismiss();
						newLoverList = mlFriendApplies;
						newLoverListAdapter.setDatas(newLoverList);
						newLoverListAdapter.notifyDataSetChanged();
					} else {
						loading.dismiss();
						newLoverList = mlFriendApplies;
						linBlank.setVisibility(View.VISIBLE);
						newLoverListAdapter.setDatas(newLoverList);
						newLoverListAdapter.notifyDataSetChanged();
					}
				} else {
					// 已加载完全部，取消loading
					// Log.e("====mlFriendApplies", "nothing" + e.getMessage());

				}
			}

		});
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		if (position - 1 < 0 || newLoverListAdapter.getCount() <= 0) {
			return;
		}
		MLUserLike selectUser = (MLUserLike) newLoverListAdapter
				.getItem(position - 1);
		String selectedUserId = selectUser.getUser().getObjectId();
		Intent intent = new Intent(NewLover.this, Profile.class);
		intent.putExtra("userId", selectedUserId);
		intent.putExtra("nickname", selectUser.getUser().getNickname());
		startActivity(intent);

	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
	}

}
